import requests,os,time

import platform
requests.packages.urllib3.disable_warnings()
import ssl
import json
ssl._create_default_https_context = ssl._create_unverified_context
import httplib2
httplib2.HTTPConnectionWithTimeout._http_vsn=10
httplib2.HTTPConnectionWithTimeout._http_vsn_str = 'HTTP/1.0'
import sys
print(sys.getrecursionlimit())
sys.setrecursionlimit(65530)

requests.DEFAULT_RETRIES = 100
# requests.adapters.DEFAULT_RETRIES = 20

# import requests
# from requests.adapters import HTTPAdapter
# from requests.packages.urllib3.util.retry import Retry
#
#
# class RetryAfterCustomSleep(Retry):
#     def sleep(self):
#         if self.backoff_factor is not None:
#             sleep_time = self.backoff_factor * (2 ** self.retries)
#             time.sleep(sleep_time)

# 尝试增加缓冲区大小

import urllib3, socket
from urllib3.connection import HTTPConnection

HTTPConnection.default_socket_options = (
        HTTPConnection.default_socket_options + [
    (socket.SOL_SOCKET, socket.SO_SNDBUF, 1000000),  # 1MB in byte
    (socket.SOL_SOCKET, socket.SO_RCVBUF, 1000000)
])
# 定义会话
session = requests.Session()

# 设置重试策略
# retries = RetryAfterCustomSleep(total=5, backoff_factor=1)
# adapter = HTTPAdapter(max_retries=retries)
#
# # 为所有支持的方法配置适配器
# session.mount('http://', adapter)
# session.mount('https://', adapter)



# print(HTTPConnection.default_socket_options)


def get_headers():

    headers = {
        # "Cookie": "user_uuid=" + str(user_uuid),
        # "Accept":"*/*",
        # "Accept-Encoding":"gzip, deflate, br, zstd",
        # "Accept-Language":"zh-CN,zh;q=0.9",
        "Dnt": "1",
        "Referer":"https://www.fofoyy.com",
        "Priority":"u=1, i",
        "Sec-Ch-Ua": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
        "Sec-Ch-Ua-Mobile": "?0",
        "Sec-Ch-Ua-Platform": "Windows",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "cross-site",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",

    }
    return headers

headers = get_headers()
# session = requests.Session()


def convert_ts_to_mp4(ts_file_path, mp4_file_path):
    # 将ts文件转为mp4文件
    #
    print(" convert_ts_to_mp4",ts_file_path, mp4_file_path)

    os.system(f'ffmpeg -i {ts_file_path} -c copy {mp4_file_path}')


def down_all234(url,filename,data):
    # 下载ts文件到一个文件，且将ts文件转为mp4文件
    # url = "https://v.cdnlz16.com/20230911/38410_55a88c1c/2000k/hls/mixed.m3u8"

    # filename = "1"
    # 将中文名称改为16禁止
    # import base64
    # import binascii
    # filename = base64.b64encode(filename.encode())
    # hex_string = binascii.b2a_hex(filename).decode()
    # filename = hex_string
    filename=filename.strip()
    if '[' in filename:
        filename=filename.split('[')[0]
    if platform.system() == "Windows":  # Windows Linux
        ts_file_path = r'C:\1\BaiduSyncdisk'
        mp4_file_path = r'C:\1\video'
        print("创建文件加1")
        os.makedirs(ts_file_path, exist_ok=True)
        os.makedirs(mp4_file_path, exist_ok=True)

    else:
        ts_file_path = r'/video'
        mp4_file_path = r'/video'
    ts_filename = filename + ".ts"
    mp4_filename = filename + ".mp4"


    if mp4_filename in os.listdir(mp4_file_path):
        pass
    else:
        # mp4_filename_ori =
        ts_file_path = os.path.join(ts_file_path, ts_filename)
        print("ts_file_path", ts_file_path)
        mp4_file_path = os.path.join(mp4_file_path, mp4_filename)
        print("mp4_filename", mp4_file_path)
        flag = direct_down_m3u8(url, ts_file_path,data)
        if flag == False:
            pass
        else:

            # 转换ts文件为mp4
            convert_ts_to_mp4(ts_file_path, mp4_file_path)
            time.sleep(20)

            # 删除ts文件
            from missav.test_file import rm
            if os.path.exists(mp4_file_path):
                rm(path=ts_file_path)
            if not  os.path.getsize(ts_file_path):
                # 判断文件是否为空
                rm(path=ts_file_path)


def direct_down_m3u8(m3u8_list,file_path,data):

    while True:
        try:
            cryptor = None # 加密的实例
            method = None # m3u8文件是否加密
            count = 0
            failed_count=0 # 统计失败次数
            with open(file_path, 'ab') as f:

                for ts_url in m3u8_list[1:]:
                    try:
                        print("正在下载：\t" + file_path + ts_url)
                        print("正在下载：\t" + ts_url)
                        # break_url = m3u8_list.index(ts_url)
                        # print("break_url_open1", count)
                        # count +=1

                        # proxies = get_proxy()
                        # print("proxies", proxies)
                        import re
                        from Crypto.Cipher import AES


                        if "#EXT-X-KEY:METHOD=AES-128" in ts_url:
                        #     在这里设置解密的
                            method = re.findall('#EXT-X-KEY:METHOD=(.*?),', ts_url)[0]
                            print(method,ts_url)
                            key = re.findall('#EXT-X-KEY:METHOD=AES-128,URI="(.*?)"', ts_url)
                            key_url = key[0]
                            print("key_url1",key_url)
                            if "http" not in key_url:
                                # key_url='/'.join(m3u8_list[0].split('/')[:-1])+'/'+key_url
                                key_url=m3u8_convert(m3u8_list[0],key_url)
                            print("key_url2", key_url)

                            res = requests.get(key_url, headers=headers, timeout=100, verify=False)
                            if res.status_code != 200:
                                continue
                            key = res.content
                            try:
                                iv = ts_url.split('IV=')[-1]
                                print("iv-1",iv)
                                if iv != '0x00000000000000000000000000000000':
                                    iv = '0x00000000000000000000000000000000'
                                # if iv:
                                #     iv = iv

                            except Exception as e:
                                print("error1",e)
                                iv='0x00000000000000000000000000000000'

                            iv = iv.replace('0x', '')
                            iv = bytes.fromhex(iv)
                            print("iv-value",iv)
                            cryptor = AES.new(key, AES.MODE_CBC, iv)
                            print("key_url2", key_url)
                            continue
                            # exit()
                        # exit()
                        elif "#EXT-X-KEY:METHOD=NONE" in ts_url:
                            method =None
                            continue

                        with session.get(ts_url, headers=headers, verify=False, stream=True, timeout=1000) as r:
                            print("write file status",r.status_code)

                            if r.status_code == 200:
                                # print("status_code_ts_url", r.status_code, ts_url)
                                # if data is not None:
                                #     cryptor = data[1]
                                #     f.write(cryptor.decrypt(r.content))
                                # else:
                                if method is not None:
                                    # cryptor = data[1]
                                    f.write(cryptor.decrypt(r.content))
                                    count=count+1;
                                    # if count >20:
                                    #     return True
                                else:
                                    f.write(r.content)
                            else:
                                time.sleep(10)
                                failed_count=failed_count+1;
                                if failed_count>20:
                                    break
                    except Exception as e:
                        print("error1",e)
                        continue


        except Exception as e:
            # time.sleep(10)
            print("break_url", e) #break_url list index out of range
            if "No space left on device" in str(e):
                os._exit(os.EX_OK)
            continue
        break
    print('m3u8视频下载完成')
    return True


def get(url):
    try:
        # proxies = get_proxy()
        if url is not None:
            print("get---msg",url)
            # session = requests.Session()
            # return session.get(url, headers=headers, timeout=10, verify=False)
            return session.get(url, headers=headers,  timeout=100, verify=False)
    except Exception as e:
        print("get---msg \t",e)
        if "NameResolutionError" in e:
            pass
        else:
            get(url)


def down12345(d,filename):
    '''
    d 是一个m3u8链接
    filename 是获取的movie的名字
    '''
    url_sssss = ""
    try:

        if "index.m3u8" not in d:
            pass
        print("ddd", d,filename)
        res = get(d)
        print("status_code_ddddddddd", res.status_code)

        if res.status_code == 200:
            res_content = res.text
            # with open('test.text','w') as f:
            #     f.write(res_content)

            if "m3u8" in res_content :
                # 如果响应内容只有一个m3u8链接
                print("果响应内容只有一个m3u8链接")
                # m3u8_convert 将源url和m3u8文件的url进行整合
                # url1 = d.split('/')[:-1]
                t = [ m3u8_convert(d, i) for i in res_content.split('\n') if i and i[0] != '#']
                print("只有一个m3u8链接",t)
                # if len(t)==1:
                #     '''
                    # /20240619/YwHpcV7L/2000kb/hls/index.m3u8
                    # https://s10.fsvod1.com/20240619/YwHpcV7L/index.m3u8
                    # '''
                    # print("url2",t[0])
                    # print("url2",url1)
                    # url3 = t[0].split('/')
                    # for i in url3:
                    #     if i !="":
                    #         if i in url1:
                    #             pass
                    #         else:
                    #             url1.append(i)

                    # url2 = m3u8_convert(d, i)
                    # url2 = url1 + '/' + t[0]
                url2=t[0]
                # else:
                #     url2=t[1]
                    # url2 = "/".join(url1)
                print("url2",url2)
                down12345(url2, filename)
            # else:


                # if "https" in res_content or "http" in res_content:
            else:
                data = []
                m3u8_list = res_content.split('\n')
                m3u8_list = [ i for i in m3u8_list if i and i[0] != '#' or "#EXT-X-KEY:METHOD=AES-128" in i ]
                # m3u8_list = [ i for i in m3u8_list if 'http' not in i ]
                data1=[]

                data1.append(d)
                print("ts",m3u8_list)
                # url=""
                # https://jpzy01.com/20240617/0hX4bLa4/3869kb/hls/20240807/JC8Ofeh4/800kb/jZwWv7fr.jpg
                # https://jpzy01.com/hls/20240807/JC8Ofeh4/800kb/jZwWv7fr.jpg
                # https://jpzy01.com/20240807/JC8Ofeh4/800kb/jZwWv7fr.jpg
                # https://leduocdn.com/20240807/JC8Ofeh4/800kb/jZwWv7fr.jpg
                for i in m3u8_list:
                    if i.startswith('/'):
                        # url = m3u8_convert(d, i)
                        # print("url3",url)

                        data1.append( m3u8_convert(d,i))
                        # pass
                    else:
                        data1.append(i)
                print("direct_url_list",data1)
                print("direct_url_list",len(data1))
                if len(data1) <100:
                    raise  Exception
                # exit(0)
                down_all234(data1, filename,data)
                # else:
                #     m3u8_list = res_content.split('\n')
                #     # url1 = d.split('/')[:-1]
                #     m3u8_list = [m3u8_convert(d,i) for i in m3u8_list if i and i[0] != '#' or "#EXT-X-KEY:METHOD=AES-128" in i ]
                #
                #     print("direct_url_list2", m3u8_list)
                #     print("direct_url_list2", len(m3u8_list))
                #     down_all234(m3u8_list, filename, data)


    except Exception as e:
        print("url2222222222", e,url_sssss)



def m3u8_convert(url1,url2):
    '''
    url1 https://s10.fsvod1.com/20240619/YwHpcV7L/index.m3u8
    url2 /20240619/YwHpcV7L/2000kb/hls/index.m3u8
    '''
    if "http" in url2:
        return url2
    else:
        url1 = url1.split('/')[:-1]
        url2=url2.split('/')
        if "hls" in url2:
            url1 = url1[:3]
            return '/'.join(url1) + '/'.join(url2)
        for i in url2:
            if i != "":
                if i in url1:
                    pass
                else:
                    url1.append(i)


        return '/'.join(url1)



if __name__ == '__main__':
    # s1 ="https://s10.fsvod1.com/20240619/YwHpcV7L/index.m3u8"
    # s2="时光代理人_第01集"
    #
    # down12345(s1,s2)
    pass